package com.seeyon.apps.kk.manager.caigoudatasync;

import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.Constants.ATTACHMENT_TYPE;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.form.modules.serialNumber.SerialNumberManager;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.kk.utils.CAP4FormKitUtils;
import com.seeyon.kk.utils.CaigouStopUtils;
import com.seeyon.kk.utils.ValueUtils;

public class CaigouAbstractDataSyncManager extends CAbstractDataSyncManager {
	private static final Log log = LogFactory.getLog(CaigouAbstractDataSyncManager.class);
	private String sourceJdbcTemplateBeanId;
	private FreemarkFlowManager freemarkFlowManager;
	private static JdbcTemplate jdbc = (JdbcTemplate) AppContext.getBean("ghrjdbcTemplate");
	private String sourceDeleteSql;
	private String sourceFindInsertSql;
	private String sourceInsertSql;
	private String orcleFindAndContrastSql;
	private String oracleupdateBtSql;
	private String sourceUpdateSql;
	private String adminLoginName;
	private String templateCode;
	private String addFindArray;
	private String addCreateXMLFtl;
	private String oracleFindFormmainSql;
	
	protected ColManager colManager;
	protected TemplateManager templateManager;
	protected EnumManager enumManagerNew;	 
	protected CAP4FormManager formManager; 
	protected CAP4FormDataManager formDataManager; 
	private AttachmentDAO attachmentDAO;
	private FileManager fileManager;
	private OrgManager orgManager;

	public String getOracleFindFormmainSql() {
		return oracleFindFormmainSql;
	}

	public void setOracleFindFormmainSql(String oracleFindFormmainSql) {
		this.oracleFindFormmainSql = oracleFindFormmainSql;
	}

	public String getAddCreateXMLFtl() {
		return addCreateXMLFtl;
	}

	public void setAddCreateXMLFtl(String addCreateXMLFtl) {
		this.addCreateXMLFtl = addCreateXMLFtl;
	}

	public String getSourceJdbcTemplateBeanId() {
		return sourceJdbcTemplateBeanId;
	}

	public void setSourceJdbcTemplateBeanId(String sourceJdbcTemplateBeanId) {
		this.sourceJdbcTemplateBeanId = sourceJdbcTemplateBeanId;
	}

	public String getAddFindArray() {
		return addFindArray;
	}

	public void setAddFindArray(String addFindArray) {
		this.addFindArray = addFindArray;
	}

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	public String getSourceDeleteSql() {
		return sourceDeleteSql;
	}

	public void setSourceDeleteSql(String sourceDeleteSql) {
		this.sourceDeleteSql = sourceDeleteSql;
	}

	public String getSourceFindInsertSql() {
		return sourceFindInsertSql;
	}

	public void setSourceFindInsertSql(String sourceFindInsertSql) {
		this.sourceFindInsertSql = sourceFindInsertSql;
	}

	public String getSourceInsertSql() {
		return sourceInsertSql;
	}

	public void setSourceInsertSql(String sourceInsertSql) {
		this.sourceInsertSql = sourceInsertSql;
	}

	public String getOrcleFindAndContrastSql() {
		return orcleFindAndContrastSql;
	}

	public void setOrcleFindAndContrastSql(String orcleFindAndContrastSql) {
		this.orcleFindAndContrastSql = orcleFindAndContrastSql;
	}

	public String getOracleupdateBtSql() {
		return oracleupdateBtSql;
	}

	public void setOracleupdateBtSql(String oracleupdateBtSql) {
		this.oracleupdateBtSql = oracleupdateBtSql;
	}

	public String getSourceUpdateSql() {
		return sourceUpdateSql;
	}

	public void setSourceUpdateSql(String sourceUpdateSql) {
		this.sourceUpdateSql = sourceUpdateSql;
	}

	public String getAdminLoginName() {
		return adminLoginName;
	}

	public void setAdminLoginName(String adminLoginName) {
		this.adminLoginName = adminLoginName;
	}

	public String getTemplateCode() {
		return templateCode;
	}

	public void setTemplateCode(String templateCode) {
		this.templateCode = templateCode;
	}
	 SerialNumberManager serialNumberManager=(SerialNumberManager) AppContext.getBean("serialNumberManager");
	 
		
		
	/*
	 * @删除临时表数据
	 */
	@Override
	public boolean beforeGrabData() {
		if (StringUtils.isNotEmpty(this.sourceDeleteSql)) {
			String sql = this.freemarkFlowManager.fltTemplateIntoString(this.sourceDeleteSql, null);
			this.jdbcTemplate.update(sql);
		}
		return false;
	}
	
	/*
	 * @查询第三方数据并新增
	 */
	@Override
	public boolean sourceFindAndInsertSqlFtl() {
		if (StringUtils.isNotEmpty(this.sourceJdbcTemplateBeanId)) {
			JdbcTemplate sourceJdbc = (JdbcTemplate) AppContext.getBean(this.sourceJdbcTemplateBeanId);
			String sql = this.freemarkFlowManager.fltTemplateIntoString(sourceFindInsertSql, null);
			List<Map<String, Object>> vl = sourceJdbc.queryForList(sql);
			if (!vl.isEmpty()) {
				String[] batchinsertSql = new String[vl.size()];
				int i = 0;
				for (Iterator<Map<String, Object>> iterator = vl.iterator(); iterator.hasNext();) {
					Map<String, Object> map = iterator.next();
					batchinsertSql[i] = this.freemarkFlowManager.fltTemplateIntoString(sourceInsertSql, map);
					i++;
				}
				this.jdbcTemplate.batchUpdate(batchinsertSql);
			}
		}
		return false;
	}
	
	//临时表数据对比代办数据 如订单号相同 流程终止
	@Override
	public boolean sourceFindAndContrastSqlFtl() {
		if (StringUtils.isNotEmpty(this.oracleFindFormmainSql)) {
			try {
			String sql = this.freemarkFlowManager.fltTemplateIntoString(oracleFindFormmainSql, null);
			List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
			for (Map<String, Object> map : queryForList) {
				if(MapUtils.getString(map, "EBELN") !=null) {
				String sql2 = this.freemarkFlowManager.fltTemplateIntoString(orcleFindAndContrastSql,map);
					List<Map<String, Object>> queryForList2 = this.jdbcTemplate.queryForList(sql2);
					for (Map<String, Object> map2 : queryForList2) {
						CaigouStopUtils.getDept(map2);//流程终止接口
						this.test(map2);//qian'zhang
					}
				}
			}
			for (Iterator<Map<String, Object>> iterator = queryForList.iterator(); iterator.hasNext();) {
				Map<String, Object> map = iterator.next();
				Date ifdate = new Date();
				String ifdate1 = DateFormatUtils.format(ifdate, "yyyy-MM-dd");
				String DJBH=this.serialNumberManager.getSerialNumberValue(Long.valueOf("8734925905573654567"));
				map.put("DDDH", ifdate1);
				map.put("SEA", "1");
				map.put("CGLX", "采购审批");
				map.put("CGZT", "待审核");
				map.put("DJBH", DJBH);
				String ZEMAIL1=MapUtils.getString(map, "ZEMAIL1");//审批人一
				String ZEMAIL2=MapUtils.getString(map, "ZEMAIL2");//审批人二
				if(ZEMAIL2!=null &&!ZEMAIL2.equals("")) {
					ZEMAIL1+=","+ZEMAIL2;
				}
				map.put("Agree", ZEMAIL1);
				String newArrayList = this.freemarkFlowManager.fltTemplateIntoString(addFindArray, null);
				List<Map<String, Object>> zhiqueryForList = this.jdbcTemplate.queryForList(newArrayList,MapUtils.getString(map, "EBELN"));
				Double num = 0.00;
				for (Map<String, Object> map2 : zhiqueryForList) {
					num += MapUtils.getDouble(map2, "NETWR");
				}
				map.put("Array", zhiqueryForList);
				map.put("ZJE", num);
				String xmlData = freemarkFlowManager.fltTemplateIntoString(addCreateXMLFtl, map);
				long sendCollaboration = this.freemarkFlowManager.sendCollaboration(MapUtils.getString(map, "LOGINNAME"), this.templateCode,null, xmlData, null, "0", null);
				log.info("KK.自动发起流程成功" +sendCollaboration);
			}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return false;
	}
	
	//修改第三方表字段的状态
	@Override
	public boolean sourceUpdate() {
		if (StringUtils.isNotEmpty(this.sourceJdbcTemplateBeanId)) {
			JdbcTemplate sourceJdbc= (JdbcTemplate) AppContext.getBean(sourceJdbcTemplateBeanId);
			String sql = this.freemarkFlowManager.fltTemplateIntoString(sourceFindInsertSql, null);
			List<Map<String, Object>> queryForList = sourceJdbc.queryForList(sql);
			for (Map<String, Object> map : queryForList) {
				String updateSql = this.freemarkFlowManager.fltTemplateIntoString(sourceUpdateSql, map);
				this.jdbc.update(updateSql);
			}
		}
		return false;
	}

	
	 public void test(Map<String,Object> map2) {
		 Long summaryID=MapUtils.getLong(map2, "summaryId");
		 Long affairmember=MapUtils.getLong(map2, "memberId");
		 Long affairId=MapUtils.getLong(map2, "affriaId");
		 try {
			 colManager=(ColManager)AppContext.getBean("colManager");
			 templateManager=(TemplateManager)AppContext.getBean("templateManager");
			 formManager=(CAP4FormManager)AppContext.getBean("cap4FormManager");
			 
			 attachmentDAO=(AttachmentDAO)AppContext.getBean("attachmentDAO");
			 fileManager=(FileManager)AppContext.getBean("fileManager");
			 orgManager=(OrgManager)AppContext.getBean("orgManager");
			 
			ColSummary summary = this.colManager.getColSummaryById(summaryID); // 获取协同信息
				CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
				FormBean formBean = this.formManager.getFormByFormCode(template);
				FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
						formBean, null);
				Map<String, Object> formdata = formMasterBean.getAllDataMap();

				// 抄送人
				FormFieldBean csTFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("抄送-填写");
				if (csTFfb != null) {
					String csTMembers = MapUtils.getString(formdata, csTFfb.getName());
					FormFieldBean csXFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("抄送-显示");
					if (csTMembers != null) {
						String csXMembers = MapUtils.getString(formdata, csXFfb.getName()) + "," + csTMembers;
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-显示", csXMembers);
						CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);
					}
				}
				CAP4FormKitUtils.setCellValue(formMasterBean, "抄送-填写", null);

				
				Boolean needSave = false;

				// 这里需要根据用户 获取到个性化的签名，如果没有 则使用默认的
				Long defaultNoImageId = ValueUtils.getConfig().getLong("kk.defaultNoImageId");
				
				String imageSql = "SELECT c1.FILE_URL deyes,c2.FILE_URL deno FROM FORMMAIN_0138"
						+ " LEFT JOIN CTP_ATTACHMENT c1 ON FORMMAIN_0138.FIELD0002 = c1.SUB_REFERENCE"
						+ " LEFT JOIN CTP_ATTACHMENT c2 ON FORMMAIN_0138.FIELD0005 = c2.SUB_REFERENCE"
						+ " WHERE FIELD0001=?";
				List<Map<String, Object>> ImgId = this.jdbcTemplate.queryForList(imageSql, affairmember);
				if(ImgId.size()>0){
					Map<String, Object> temp = ImgId.get(0);
					defaultNoImageId = MapUtils.getLong(temp, "deno");
				}
				V3XFile defaultNoImageFile = this.fileManager.getV3XFile(defaultNoImageId);
				V3XFile vfile = defaultNoImageFile;
			
				String commentString = "";
				V3xOrgMember aMember = this.orgManager.getMemberById(affairmember);

				for (int i = 1; i <= 9; i++) {
					if (needSave) {
						// 有一个意见匹配需要更新
						break;
					}
					String spName = "审批" + i + "-姓名";
					String spTime = "审批" + i + "-日期";
					String spPost = "审批" + i + "-职位";
					String spImage = "审批" + i + "-签名";
					if (i == 5) {
						spName = "人事节点";
						spTime = "人事日期";
						spPost = "人事岗位";
						spImage = "人事签名";
					}
					if (i > 5) {
						spName = "审批" + i;
						spTime = "审批" + i + "-日期";
						spPost = "审批" + i + "-职位";
						spImage = "审批" + i + "-签名";
					}
					FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay(spName);
					if (spFfb == null) {
						continue;
					}
					Long memberId = MapUtils.getLong(formdata, spFfb.getName());

					if (affairmember.equals(memberId)) {
						// 赋值意见和态度
						CAP4FormKitUtils.setCellValue(formMasterBean, spTime, commentString);
						CAP4FormKitUtils.setCellValue(formMasterBean, spPost, aMember.getOrgPostId());
						needSave = true;
						FormFieldBean spImagefb = formMasterBean.getFormTable().getFieldBeanByDisplay(spImage);
						Long attReferenceid = MapUtils.getLong(formdata, spImagefb.getName());
						if (attReferenceid != null) {
							// this.attachmentDAO.deleteByReference(attReferenceid);
						}
						long subReference = UUIDLong.longUUID();
						Attachment att = new Attachment(vfile, ApplicationCategoryEnum.collaboration,
								ATTACHMENT_TYPE.IMAGE);
						att.setReference(summaryID);
						att.setSubReference(subReference);
						att.setIdIfNew();
						this.attachmentDAO.save(att);
						CAP4FormKitUtils.setCellValue(formMasterBean, spImage, subReference);
					}

				}
				if (needSave) {
					this.formManager.saveOrUpdateFormData(formMasterBean, formBean.getId(), true);
				}
		} catch (DataAccessException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	 }
	 
	
}
